package org.glavo.bot

import kotlinx.serialization.json.*
import net.mamoe.mirai.message.data.Image
import net.mamoe.mirai.message.data.Image.Key.queryUrl
import java.net.URL
import java.text.SimpleDateFormat
import java.util.regex.Matcher
import java.util.regex.Pattern

val dateFormat = SimpleDateFormat("yyyy-MM-dd_HHmmss").apply { isLenient = false }

inline fun Pattern.tryMatch(str: CharSequence, action: (Matcher) -> Unit) {
    val m = this.matcher(str)
    if (m.matches()) {
        action(m)
    }
}

suspend fun Image.asJson(): JsonObject {
    val url = this.queryUrl()
    return buildJsonObject {
        put("text", JsonCache.IMAGE_STR)
        put("underlined", JsonCache.TRUE)
        putJsonObject("clickEvent") {
            put("action", JsonCache.OPEN_URL)
            put("value", url)
        }
        put("hoverEvent", JsonCache.IMAGE_HOVER_EVENT)
    }
}

private val ipApi =
    URL("https://ip.42.pl/short")

fun serverIp(): String {
    return ipApi.readText().trim()
}
